// 负责用户部分数据操作
// 导入操作数据库的配置
const db = require('../config/db');
const aes = require('../common/aes');
const Jwt = require('../common/jwt');
const Email = require('../common/emailApi');
const host = require('../config/host');
// 步骤：1.0 生成token  2. 校验token    token: 用户的临时身份（设置登录时效）

// 测试以下
// console.log('测试：',aes.aesDecrypt('1111','$2a$10$70FdA4ZbBTwei'));
// 导出当前数据模型
module.exports = {
    // 1. 注册
    register(user_id, user_acc, user_pwd, user_nick_name, user_create_time) {
        // 检查代码有没有执行到此处
        // console.log({user_id,user_acc,user_pwd,user_nick_name,user_create_time});
        // console.log(`select user_id from c_user where user_acc='${user_acc}'`)
        return new Promise((resolve, reject) => {
            // 对密码加密
            let pwd = aes.aesEncrypt(user_pwd);//加密
            // let pwd = user_pwd
            // 判断账号是否存在
            db.query(`select user_id from c_user where user_acc='${user_acc}'`)
                .then(
                    rows => {
                        // rows 是个数组
                        // console.log('1.0',rows);// []
                        let user_picUrl = `${host.url}/images/photo-1675611586137.jpeg`;
                        // 判断账号是否已经注册
                        if (rows.length == 0) {
                            // 表示没有注册 , 添加数据
                            db.query(`insert into c_user(user_id,user_acc,user_pwd,user_nick_name,user_create_time,user_picUrl) values('${user_id}','${user_acc}','${pwd}','${user_nick_name}','${user_create_time}','${user_picUrl}')`)
                                .then(
                                    result => {
                                        resolve({
                                            code: 200,
                                            msg: '恭喜您，注册账号成功。',
                                            user_nick_name
                                        })
                                    }
                                )
                                .catch(
                                    error => {
                                        reject({ code: 500, msg: '注册账号失败。', error })
                                    }
                                )
                        }
                        else {
                            // 表示已经注册
                            resolve({
                                code: 201,
                                msg: '该账号已经存在。请登录即可'
                            })
                        }
                    }
                )
                .catch(
                    err => {
                        reject({ code: 500, msg: '注册时查询账号失败。', err })
                    }
                )
        })
    },

    // 2. 登录
    login(user_acc, user_pwd) {
        return new Promise((resolve, reject) => {
            db.query(`select user_acc,user_pwd, user_nick_name,user_create_time, user_id from c_user where user_acc = '${user_acc}'`)
                .then(
                    rows => {
                        // console.log('1.0',rows);
                        // console.log(rows[0]);
                        // console.log(user_pwd, rows[0].user_pwd)
                        // rows[用户信息]
                        // console.log('状态:', aes.aesDecrypt(user_pwd, rows[0].user_pwd));

                        // if(user_pwd === rows[0].user_pwd){
                        if (aes.aesDecrypt(user_pwd, rows[0].user_pwd)) {// 解密
                            // 生成token
                            let jwt = new Jwt(rows[0].user_id, 120);
                            let token = jwt.getToken();
                            // 删除验证码
                            Email.removeEmailCode(user_acc);
                            // 等于true表示登录成功
                            resolve({
                                code: 200,
                                msg: '登录成功。',
                                token,
                                user_nick_name: rows[0].user_nick_name
                            })
                        }
                        else {
                            // 否则 登录失败
                            resolve({
                                code: -1,
                                msg: '用户登录失败。'
                            })
                        }
                    }
                )
                .catch(
                    error => {
                        reject({ code: 500, msg: '查询用户失败。', error })
                    }
                )
        })
    },

    // 3. 注销(删除账号)
    remove(user_id) {
        return new Promise((resolve, reject) => {
            db.query(`select user_acc from c_user where user_id = '${user_id}'`)
                .then(
                    rows => {
                        if (rows.length == 1) {
                            // 有 再删除
                            db.query(`delete from c_user where user_id = '${user_id}'`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: '删除账号成功。',
                                            content
                                        })
                                    }
                                )
                                .catch(
                                    err => {
                                        reject({
                                            code: -1,
                                            msg: '删除账号失败。',
                                            err
                                        })
                                    }
                                )
                        }
                        else {
                            // 无 不用删除
                            resolve({
                                code: 404,
                                msg: '该账号不存在。'
                            })
                        }
                    }
                )
                .catch(
                    error => {
                        reject({
                            code: 500,
                            msg: '查询用户失败。',
                            error
                        })
                    }
                )
        })
    },

    // 4. 获取用户头像
    getPicUrl(user_id) {
        return new Promise((resolve, reject) => {
            // 执行sql语句
            db.query(`select user_picUrl from c_user where user_id = '${user_id}'`)
                .then(
                    rows => {
                        // 用户头像
                        let user_url = rows[0].user_picUrl ;
                        // 执行符合条件的回调
                        resolve({
                            code: 200,
                            msg: '获取用户头像成功。',
                            user_url
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '获取用户头像失败。'
                        })
                    }
                )

        })
    },


    // 5. 获取用户资料
    getUserInfo(user_id) {
        return new Promise((resolve, reject) => {
            // 执行sql语句
            db.query(`select user_acc, user_nick_name,user_create_time,user_picUrl,user_sex,user_age,user_address from  c_user where user_id = '${user_id}'`)
                .then(
                    rows => {
                        resolve({
                            code: 200,
                            msg: '获取用户资料成功。',
                            result: [...rows]
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '获取用户资料失败。',
                            err
                        })
                    }
                )
        })
    },

    // 6. 设置用户头像
    setPicUrl(user_id, user_picUrl) {
        return new Promise((resolve, reject) => {
            // 修改用户头像
            let sql = `update c_user set user_picUrl= '${user_picUrl}' where  user_id= '${user_id}'`;
            db.query(sql)
                .then(
                    content => {
                        resolve({
                            code: 200,
                            msg: '更新用户头像成功。',
                            content
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '更新用户头像失败',
                            err
                        })
                    }
                )
        })
    },

    // 7. 设置用户资料
    setUserInfo(user_id, user_nick_name, user_sex, user_age, user_address) {
        return new Promise((resolve, reject) => {
            // 修改用户头像
            let sql = `update c_user set user_nick_name= '${user_nick_name}',user_sex= '${user_sex}',user_age= '${user_age}',user_address= '${user_address}' where  user_id= '${user_id}'`;
            db.query(sql)
                .then(
                    content => {
                        resolve({
                            code: 200,
                            msg: '修改用户资料成功。',
                            content
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '修改用户资料失败',
                            err
                        })
                    }
                )
        })
    },

    // 8. 找回密码
    findPwd(user_acc, new_user_pwd) {
        return new Promise((resolve, reject) => {
            let sql = `select user_acc from c_user where user_acc = '${user_acc}'`;
            db.query(sql)
                .then(
                    rows => {
                        if (rows.length == 1) {
                            //  重新设置密码
                            db.query(`update c_user set user_pwd= '${new_user_pwd}' where  user_acc= '${user_acc}'`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: '重置密码成功。'
                                        })
                                    }
                                )
                                .catch(error => {
                                    reject({
                                        code: -1,
                                        msg: '重置密码失败。',
                                        error
                                    })
                                })
                        }
                        else {
                            resolve({
                                code: 404,
                                msg: '该账号不存在。'
                            })
                        }
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '找回密码时，查询用户失败。',
                            err
                        })
                    }
                )
        })
    },


    // 9. 邮箱登录
    emailLogin(user_acc) {
        return new Promise((resolve, reject) => {
            db.query(`select user_acc,user_pwd, user_nick_name,user_create_time, user_id from c_user where user_acc = '${user_acc}'`)
                .then(
                    rows => {
                        if (rows.length == 1) {
                            // 生成token
                            let jwt = new Jwt(rows[0].user_id, 120);
                            let token = jwt.getToken();
                            // 删除验证码
                            Email.removeEmailCode(user_acc);
                            // 等于true表示登录成功
                            resolve({
                                code: 200,
                                msg: '用户登录成功。',
                                token,
                                user_nick_name: rows[0].user_nick_name
                            })
                        }
                        else {
                            resolve({
                                code: -1,
                                msg: '用户登录失败。'
                            })
                        }
                    }
                )
                .catch(
                    error => {
                        reject({ code: 500, msg: '查询用户失败。', error })
                    }
                )
        })
    },

    // 10. 用户登录状态
    onLine(user_id){
        return new Promise((resolve,reject)=>{
            db.query(`select user_nick_name, user_picUrl from c_user where user_id = '${user_id}'`)
            .then(
                rows=>{
                    if(rows.length == 1){
                        resolve({
                            code: 200,
                            msg: '处于登录状态',
                            user_nick_name: rows[0].user_nick_name,
                            user_picUrl: rows[0].user_picUrl,
                        })
                    }
                    else {
                        resolve({
                            code: 404,
                            msg: '没有该用户'
                        })
                    }
                }
            )
            
        })
    }
}